package me.zhengjie.modules.hanzi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.hanzi.domain.HanziCharacter;
import me.zhengjie.modules.hanzi.domain.UserProgress;
import me.zhengjie.modules.hanzi.mapper.UserProgressMapper;
import me.zhengjie.modules.hanzi.mapper.CharacterMapper;
import me.zhengjie.modules.hanzi.domain.Category;
import me.zhengjie.modules.hanzi.mapper.CategoryMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
@RequiredArgsConstructor
public class UserProgressService extends ServiceImpl<UserProgressMapper, UserProgress> {
    private final UserProgressMapper userProgressMapper;
    private final CharacterMapper characterMapper;
    private final CategoryMapper categoryMapper;

    public Map<String, Object> getUserProgress(Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取学习统计
        QueryWrapper<UserProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        long learnedCount = userProgressMapper.selectCount(wrapper);
        
        result.put("learnedCount", learnedCount);
        result.put("totalCount", characterMapper.selectCount(null));
        result.put("daysStreak", calculateDaysStreak(userId));
        
        // 获取分类进度
        List<Map<String, Object>> categoryProgress = new ArrayList<>();
        List<Category> categories = categoryMapper.selectList(null);
        for (Category category : categories) {
            long categoryLearned = userProgressMapper.selectCount(
                new QueryWrapper<UserProgress>()
                    .eq("user_id", userId)
                    .inSql("character", 
                        "SELECT character FROM hanzi_character WHERE category_id = '" + category.getCategoryId() + "'")
            );
            long categoryTotal = characterMapper.selectCount(
                new QueryWrapper<HanziCharacter>()
                    .eq("category_id", category.getCategoryId())
            );
            
            Map<String, Object> catProgress = new HashMap<>();
            catProgress.put("name", category.getName());
            catProgress.put("learned", categoryLearned);
            catProgress.put("total", categoryTotal);
            catProgress.put("percent", categoryTotal > 0 ? (categoryLearned * 100 / categoryTotal) : 0);
            categoryProgress.add(catProgress);
        }
        result.put("categories", categoryProgress);
        
        // 获取最近学习的汉字
        List<Map<String, Object>> recentLearned = userProgressMapper.getRecentLearned(userId);
        result.put("recentLearned", recentLearned);
        
        return result;
    }

    private int calculateDaysStreak(Long userId) {
        // 获取用户最近的学习记录，按时间倒序排列
        List<UserProgress> records = userProgressMapper.selectList(
            new QueryWrapper<UserProgress>()
                .eq("user_id", userId)
                .orderByDesc("learn_time")
        );
        
        if (records.isEmpty()) {
            return 0;
        }

        int streak = 1;
        LocalDate lastDate = records.get(0).getLearnTime().toLocalDate();
        LocalDate today = LocalDate.now();

        // 如果最后学习日期不是今天或昨天，说明已经中断
        if (lastDate.isBefore(today.minusDays(1))) {
            return 0;
        }

        // 计算连续天数
        for (int i = 1; i < records.size(); i++) {
            LocalDate currentDate = records.get(i).getLearnTime().toLocalDate();
            if (lastDate.minusDays(1).equals(currentDate)) {
                streak++;
                lastDate = currentDate;
            } else {
                break;
            }
        }

        return streak;
    }

    public void updateProgress(Long userId, String character, String status) {
        UserProgress progress = new UserProgress();
        progress.setUserId(userId);
        progress.setCharacter(character);
        progress.setStatus(status);
        progress.setLearnTime(LocalDateTime.now());
        userProgressMapper.insert(progress);
    }
} 